package com.brozha.ans_sys.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.brozha.ans_sys.entity.News;
import com.brozha.ans_sys.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author brozha
 * @since 2021/4/8
 */
@Component
@EnableScheduling
@Slf4j
public class AnsSysScheduleTask {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    NewsService newsService;

//    //每天23点清空一次redis的username
//    @Scheduled(cron = "0 0 23 * * ?")
//    private void redisUsernameClear(){
//        log.info("开始重置redis中的set缓存username");
//        redisUtils.del("username");
//        redisUtils.sSet("username","root");
//        log.info("username重置成功");
//    }

    //每天23点更新news的库存
    @Scheduled(cron = "0 0 23 * * ?")
    private void updateNews(){
        //先从数据库中取出前80个数据到redis的set(key="news",value=newsUrl)中
        QueryWrapper<News> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time");
        qw.last("limit 80");
        List<News> redisLsit = newsService.list(qw);
        for (News news : redisLsit) {
            redisUtils.sSet("news",news.getNewsUrl());
        }
        List<News> news = newsService.crawlerTask1();
        //判断是否存在
        for (int i = 0; i < news.size(); i++) {
            if(redisUtils.sHasKey("news",news.get(i).getNewsTitle())){
                news.remove(i);
                i = i-1;
            }else{
                redisUtils.sSet("news",news.get(i).getNewsUrl());
            }
        }
        //存入数据库
        newsService.saveBatch(news);
        //定时任务结束就删除
        redisUtils.del("news");
    }
}
